let Sequelize = require('sequelize');
let {sequelize} = require('../sequelize.js');
const Op = Sequelize.Op;

let device_message = sequelize.define('device_message', {
      id: {
        type: Sequelize.BIGINT(11),
        primaryKey: true,
        allowNull: false,
        unique: true,
        autoIncrement: true
      },
      device_id: Sequelize.BIGINT(11),
      role: Sequelize.STRING(25),
      content: Sequelize.TEXT,
      create_time: Sequelize.DATE
    },
    {
      timestamps: false, // 不要默认时间戳 数据库没有时间戳字段时，设置为false，否则报错  SequelizeDatabaseError: Unknown column 'createdAt' in 'field list'
      freezeTableName: true
    }
);

class DeviceMsgObj {
  constructor() {
    this.device_message = device_message
  }

  addMessage({device_id, role, content}) {
    return this.device_message.create({
      id: 0,
      device_id: device_id,
      role: role,
      content: content,
    })
  }

  getMessageList({device_id}) {
    let where = {device_id}
    return this.device_message.findAll({where})
  }

  async getAllMessageList({content, device_id, role, dateTime, offset = 0, limit = 10}) {
    let where = {}
    if (content) where.content = {[Op.like]: `%${content}%`}
    if (device_id) where.device_id = device_id
    if (role) where.role = role
    if (dateTime) where.create_time = {[Op.between]: dateTime}
    // where.create_time = {[Op.between]: ['2023-05-04 14:34:00', '2023-05-04 14:34:37']}
    let order = [['create_time', 'desc'], ['id', 'desc']]
    let total = await this.device_message.count({where})
    let list = await this.device_message.findAll({where, order, offset, limit})
    return {total, list}
  }
}

module.exports = {
  deviceMsgObj: new DeviceMsgObj(),
};
